﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Koala.Pro.Core.Dto;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.Services;

namespace Koala.Pro.ViewModels
{
    public partial class LoginLogListViewModel : BaseListViewModel<LoginLogInfo, int, LoginLogPagedDto>
    {
        [ObservableProperty]
        private TreeViewModel<RoleAndDeptTreeNode> deptTreeModel = new TreeViewModel<RoleAndDeptTreeNode>();

        public LoginLogListViewModel(ILoginLogService service)
            : base(service)
        {
            ExportFields = "User_ID,LoginName,FullName,Company_ID,CompanyName,Note,IPAddress,MacAddress,LastUpdated,SystemType_ID";
        }

        [RelayCommand]
        private async Task GetTree()
        {
            List<RoleAndDeptTreeNode> list = AddOUNodeRecursive(await SecurityHelper.GetMyGroupCompanyTree(App.ViewModel.UserInfo));
            DeptTreeModel.TreeItems = list;
            DeptTreeModel.FilteredTreeItems = new List<RoleAndDeptTreeNode>(list);
        }

        private List<RoleAndDeptTreeNode> AddOUNodeRecursive(List<OuInfo> children, RoleAndDeptTreeNode parentNode = null)
        {
            List<RoleAndDeptTreeNode> list = new List<RoleAndDeptTreeNode>();
            foreach (OuInfo child in children)
            {
                RoleAndDeptTreeNode roleAndDeptTreeNode = new RoleAndDeptTreeNode();
                roleAndDeptTreeNode.Name = child.Name;
                roleAndDeptTreeNode.Tag = null;
                if (child.Category == "集团" || child.Category == "公司")
                {
                    roleAndDeptTreeNode.CompanyId = child.Id.ToString();
                }
                else
                {
                    roleAndDeptTreeNode.DeptId = child.Id.ToString();
                }
                parentNode?.Children.Add(roleAndDeptTreeNode);
                AddOUNodeRecursive(child.Children, roleAndDeptTreeNode);
                list.Add(roleAndDeptTreeNode);
            }
            return list;
        }
    }
}
